package com.metro.paperless.sys.beans.vo;

import com.metro.core.beans.entity.BaseEntity;
import com.metro.utils.CollectionUtil;
import lombok.Data;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 树形结构默认结构
 * Created by xk on 2018/3/4 0004.
 */
@Data
public class TreeBo extends BaseEntity {
    //父节点
    private Long parentId;
    //内部编码
    private String innerCode;
    //层级
    private Integer rank;
    //排序号
    private Integer sortNum;
    //表名称
    private String tableName;

    public static void genInnerCode(List<TreeBo> list, int length) {
        Map<Long, String> map = new HashMap<>();
        String baseCode = "00000000000000000000";
        baseCode = "1" + baseCode.substring(0, length - 1);

        //默认0是根节点
        map.put(0L, baseCode);
        String innerCode = null;
        String childCode = null;
        if(CollectionUtil.isEmpty(list)){
            return;
        }

        for(TreeBo tree : list){
            innerCode = map.get(tree.getParentId());
            if(innerCode == null){
                throw new RuntimeException("树形结构数据不正确:" + tree.getId() + " 未找到父节点");
            }
            String pre = innerCode.substring(0, innerCode.length() - length);
            String currentLevel = "" + (Integer.valueOf(innerCode.substring(innerCode.length() - length))+1);
            innerCode = pre + currentLevel;
            tree.setInnerCode(innerCode);
            map.put(tree.getParentId(), innerCode);
            map.put(tree.getId(), innerCode + baseCode);
        }
    }
}
